/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.furb.trabalhoFinal.view;

import br.com.furb.trabalhoFinal.DAO.DAOCargo;
import br.com.furb.trabalhoFinal.DAO.DAOColaborador;
import br.com.furb.trabalhoFinal.Exceptions.ColaboradorException;
import br.com.furb.trabalhoFinal.Exceptions.DAOException;
import br.com.furb.trabalhoFinal.model.Cargo;
import br.com.furb.trabalhoFinal.model.Colaborador;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Jonathan
 */
public class ColaboradoresTela extends javax.swing.JFrame {

    private DAOColaborador daoColaborador;
    private DAOCargo daoCargo;

    /**
     * Creates new form ColaboradoresTela
     */
    public ColaboradoresTela() {
        initComponents();
        daoColaborador = new DAOColaborador();
        daoCargo = new DAOCargo();
        cbCargo.setModel(new DefaultComboBoxModel<>(daoCargo.getCargos().values().toArray()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAlterar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        lbNumCad = new javax.swing.JLabel();
        txtNumCad = new javax.swing.JTextField();
        jSeparator3 = new javax.swing.JSeparator();
        lbNomPes = new javax.swing.JLabel();
        txtNomPes = new javax.swing.JTextField();
        lbDatNas = new javax.swing.JLabel();
        txtDatNas = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        cbCargo = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        txtSalario = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Colaborador");

        btnAlterar.setText("Alterar");
        btnAlterar.setName("btnAlterar"); // NOI18N
        btnAlterar.setNextFocusableComponent(btnCancelar);
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setName("bntCancelar"); // NOI18N
        btnCancelar.setNextFocusableComponent(btnExcluir);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.setName("btnExcluir"); // NOI18N
        btnExcluir.setNextFocusableComponent(btnSair);
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.setName("btnSair"); // NOI18N
        btnSair.setNextFocusableComponent(txtNumCad);
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        lbNumCad.setText("Número Cadastro");

        txtNumCad.setNextFocusableComponent(txtNomPes);
        txtNumCad.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNumCadFocusLost(evt);
            }
        });

        lbNomPes.setText("Nome");

        txtNomPes.setNextFocusableComponent(txtDatNas);

        lbDatNas.setText("Data Nascimento");

        try {
            txtDatNas.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtDatNas.setNextFocusableComponent(cbCargo);

        jLabel1.setText("Cargo");

        cbCargo.setNextFocusableComponent(txtSalario);
        cbCargo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cbCargoFocusGained(evt);
            }
        });

        jLabel2.setText("Salário");

        txtSalario.setNextFocusableComponent(btnAlterar);
        txtSalario.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtSalarioFocusGained(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbNomPes)
                            .addComponent(lbNumCad)
                            .addComponent(lbDatNas)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNumCad, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNomPes, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtSalario, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(cbCargo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtDatNas, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)))
                        .addGap(0, 319, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnSair, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAlterar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAlterar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancelar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnExcluir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSair)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lbNumCad)
                                    .addComponent(txtNumCad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lbNomPes)
                                    .addComponent(txtNomPes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lbDatNas)
                                    .addComponent(txtDatNas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(cbCargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel2)
                                    .addComponent(txtSalario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 446, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbCargoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbCargoFocusGained
        cbCargo.setModel(new DefaultComboBoxModel<>(daoCargo.getCargos().values().toArray()));
    }//GEN-LAST:event_cbCargoFocusGained

    private void txtSalarioFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSalarioFocusGained
        if (cbCargo.getSelectedItem() == null) {
            txtSalario.setText("");
        } else {
            txtSalario.setText(((Cargo) cbCargo.getSelectedItem()).getDescricaoCargo());
        }
    }//GEN-LAST:event_txtSalarioFocusGained

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        Colaborador colaborador = new Colaborador();

        try {
            colaborador.setNumeroCadastro(Integer.parseInt(txtNumCad.getText()));
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Valor inválido para o número do cadastro");
            return;
        } catch (ColaboradorException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
            return;
        }

        try {
            colaborador.setNome(txtNomPes.getText());
        } catch (ColaboradorException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
            return;
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            sdf.getCalendar().setLenient(false);
            colaborador.setDataNasc(sdf.parse(txtDatNas.getText()));
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "Falha na conversão da data");
            return;
        }

        try {
            colaborador.setCargo((Cargo) cbCargo.getSelectedItem());
        } catch (ColaboradorException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
            return;
        }

        try {
            Double salario = Double.parseDouble(txtSalario.getText());
            if (((Cargo) cbCargo.getSelectedItem()).getSalarioBase() <= salario) {
                colaborador.setSalario(salario);
            } else {
                JOptionPane.showMessageDialog(this, "Valor do campo salário menor que o salário definido no cargo");
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Valor inválido para o salário");
            return;
        } catch (ColaboradorException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
            return;
        }
        try {
            daoColaborador.salvar(colaborador);
        } catch (DAOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }

        limparTela();
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        limparTela();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        try {
            if (txtNumCad.getText().isEmpty()) {
                daoColaborador.excluir(Integer.parseInt(txtNumCad.getText()));
                limparTela();
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(rootPane, "Falha ao excluir cargo, o valor informado no campo codigo é inválido");
        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void txtNumCadFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNumCadFocusLost
        try {
            if (!(txtNumCad.getText().isEmpty())) {
                exibirColaborador(daoColaborador.carregar(Integer.parseInt(txtNumCad.getText())));
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Valor inválido para o número do cadastro");
            return;
        }
    }//GEN-LAST:event_txtNumCadFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ColaboradoresTela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ColaboradoresTela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ColaboradoresTela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ColaboradoresTela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ColaboradoresTela().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cbCargo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JLabel lbDatNas;
    private javax.swing.JLabel lbNomPes;
    private javax.swing.JLabel lbNumCad;
    private javax.swing.JFormattedTextField txtDatNas;
    private javax.swing.JTextField txtNomPes;
    private javax.swing.JTextField txtNumCad;
    private javax.swing.JTextField txtSalario;
    // End of variables declaration//GEN-END:variables

    private void limparTela() {
        txtNumCad.setText("");
        txtNomPes.setText("");
        txtDatNas.setText("");
        cbCargo.setSelectedItem(null);
        txtSalario.setText("");
    }

    private void exibirColaborador(Colaborador col) {
        txtNomPes.setText(col.getNome());
        txtDatNas.setText(col.getDataNasc().toString());
        cbCargo.setSelectedItem(col.getCargo());
        txtSalario.setText(Double.toString(col.getSalario()));
    }
}
